//
//  WQNetworkTool.swift
//  WeiBo
//
//  Created by Xmen on 16/9/22.
//  Copyright © 2016年 111. All rights reserved.
//

import UIKit
import AFNetworking

enum RequestType: Int {
    case POST
    case GET
}

class WQNetworkTool: AFHTTPSessionManager {

    static let sharedTool: WQNetworkTool = {
    let tools = WQNetworkTool()
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()

    //  封装get/post请求
    fileprivate func request(type: RequestType, url: String, params: Any?, callBack: @escaping (Any?, Error?)->()) {
        
        if type == .GET {
            get(url, parameters: params, progress: nil, success: { (_, response) in
                callBack(response, nil)
                }, failure: { (_, error) in
                    callBack(nil, error)
            })
            
        } else {
            post(url, parameters: params, progress: nil, success: { (_, response) in
                callBack(response, nil)
                }, failure: { (_, error) in
                    callBack(nil, error)
            })
            
        }
        
    }
    
    
    
    
}

extension WQNetworkTool {
    
    //  通过Accesstoken获取用户信息
    func requestUserInfo(accessToken: String,  callBack: @escaping (Any?, Error?) -> ()) {
        //  请求接口
        let url = "https://api.weibo.com/2/statuses/friends_timeline.json"
        //  请求参数
        let params = [
            "access_token": accessToken
        ]
        
        print(url + "?access_token=\(accessToken)")
        request(type: .GET, url: url, params: params, callBack: callBack)
        
        
    }
    



}


extension WQNetworkTool{
    func requestStatuses(accessToken: String, uid: Int64, callBack: @escaping (Any?, Error?) -> ()) -> Void {
        let url = "https://api.weibo.com/2/users/show.json"
        let params: [String: Any] = [
            "access_token": accessToken,
            "uid": uid
        ]
        
        request(type: .GET, url: url, params: params, callBack: callBack)
    }
    
     func requestAccessToken(code: String, callBack: @escaping (Any?, Error?)->()) {
        let url = "https://api.weibo.com/oauth2/access_token"
        let pararms: [String: Any] = [
            "client_id": wbAppKey,
            "client_secret": wbAppSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": wbRedirect_Uri
        ]
        request(type: .POST, url: url, params: pararms, callBack: callBack)
    }
    
    
}
